package com.hgd.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import com.hgd.DAO.AdminDAO;
import com.hgd.ORM.Admin;
import com.hgd.hibernate.HibernateUtil;

public class AdminImpl implements AdminDAO {

	public List<Admin> adminLogin(String adminName, String passsword) {
		
		//boolean result = false;
		Session session = HibernateUtil.getSesion();
		List<Admin> adminList = new ArrayList<Admin>();
		try {
			session.beginTransaction();		
			
			String hql = "FROM Admin a WHERE a.adminName=? AND a.password=?";
			adminList = session.createQuery(hql).setString(0, adminName).setString(1, passsword).list();
//			if (adminList.size()>0) {
//				result = true;
//			}else{
//				result = false;
//			}
			session.flush();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally{
			HibernateUtil.closeSession(session);
		}
		return adminList;
	}
	
	public List<Admin> getAllAdmin() {
		Session session = HibernateUtil.getSesion();
		List<Admin> adminList = new ArrayList<Admin>();
		try {
			session.beginTransaction();	
			
			adminList = session.createQuery("from Admin").list();
			
			session.flush();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally{
			HibernateUtil.closeSession(session);
		}
		return adminList;
	}

	public int adminMod(Admin admin) {
		Session session = HibernateUtil.getSesion();
		int flag = 0;
		try {
			session.beginTransaction();	
			String hql = "UPDATE Admin a SET a.adminName=?,a.email=?,a.phoneNumber=?,a.roles=? WHERE a.id=?";
			flag = session.createQuery(hql).setString(0, admin.getAdminName())
																	   .setString(1, admin.getEmail())
																	   .setString(2, admin.getPhoneNumber())
																	   .setLong(3, admin.getRoles())
																	   .setLong(4, admin.getId())
																	   .executeUpdate();
			System.out.println(flag);
			session.flush();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally{
			HibernateUtil.closeSession(session);
		}
		return flag;
	}
}
